
clear all
use "${source_data}\Customs_Data.dta", clear
set seed 10001
global isid_vars date UD_num HS6_main custom_office registration_nber itm_nber 

* ---------------------------------------------------------------------------- *
* FURTHER MERGING AND PROCESSING
* ---------------------------------------------------------------------------- *

* 1) Destinations 

capture drop _merge
sort custom_office registration_nber date itm_nber
merge 1:1 custom_office registration_nber date itm_nber using "${source_data}\Destinations_Data.dta"

capture drop xx
bys UD_num destination_bkup: egen xx=total(q_exp)
gsort UD_num -xx destination_bkup
by UD_num:  gen n=_n
gen destination_order=destination_bkup if n==1 
by UD_num: replace destination_order=destination_order[_n-1] if destination_order==.  
replace destination_order=destination_bkup if UD_num==.

* 2) Additional latex compatible labels
label var ln_p_inpf_sbjo "\$p^f_{sbjo}\$" 

* ---------------------------------------------------------------------------- *
* TABLE 1. Buyers' Concentration and Sourcing
* ---------------------------------------------------------------------------- * 

do "${floats}\Table1.do"

* ---------------------------------------------------------------------------- *
* TABLE 2. Summary Statistics
* ---------------------------------------------------------------------------- *

do "${floats}\Table2.do"

* ---------------------------------------------------------------------------- *
* TABLE C2. Sourcing Strategies, Time-Varying and Order Characteristics
* ---------------------------------------------------------------------------- *

do "${floats}\TableC2PanelA.do"
do "${floats}\TableC2PanelB.do"

* ---------------------------------------------------------------------------- *
* TABLE C11. Sourcing Strategies and Sellers' Characteristics
* ---------------------------------------------------------------------------- *

do "${floats}\TableC11.do"

* ---------------------------------------------------------------------------- *
* TABLE E3. Price of Fabric, Relationship Dynamics, and Fabric Quantities
* ---------------------------------------------------------------------------- *

rename top_dest_b DBKUP
capture drop top_dest_b
capture drop rank_dest
capture drop q_bd 
bys b_id destination_order: egen q_bd=total(q_exp)  
replace q_bd=. if destination_order==.
sort b_id q_bd custom_office registration_nber date itm_nber
by b_id: egen rank_dest=rank(-q_bd), field
capture drop zz
clonevar zz=destination_order if rank_dest==1
capture drop top_dest_b
bys b_id: egen top_dest_b=median(zz)
* The following are all order-level regressions (destination is defined at the order level)

do "${floats}\TableE3.do"

* ---------------------------------------------------------------------------- *
* TABLE 3. Buyers' Sourcing and Prices
* ---------------------------------------------------------------------------- *

do "${floats}\Table3.do"

* ---------------------------------------------------------------------------- *
* TABLE 4. Buyers' Sourcing and Input Usage
* ---------------------------------------------------------------------------- *

do "${floats}\Table4.do"

* ---------------------------------------------------------------------------- *
* Merge in elasticities for the generation of markups
* ---------------------------------------------------------------------------- *

preserve
use "${replicated_data}\Bootstrapped_Elasticities.dta", clear
gen D_sourcing=.
replace D_sourcing=1 if estimation=="theta_olsR"
replace D_sourcing=0 if  estimation=="theta_olsS"

keep if estimation=="theta_olsR" | estimation=="theta_olsS" | estimation=="theta_1_ols"

gen theta = coeff if D_sourcing ==.
replace theta = theta[_n-1] if theta==.
rename coeff theta_buyer
keep D_sourcing theta_buyer theta
sort D_sourcing

save "${replicated_data}\Preferred_Elasticities.dta", replace 
restore

sort D_sourcing
capture drop _merge
merge m:1 D_sourcing using "${replicated_data}\Preferred_Elasticities.dta"


capture drop *mu_* *mc_*
capture drop xx
bys UD_num: egen xx=total(pq_exp)
capture drop alpha_o_new
gen alpha_o_new=(p_inpf_sbjo*exp(ln_q_inpf))/xx

gen mu_o_B=(alpha_o_new)^(-1)*theta
gen mc_o_B=p_sbjo/mu_o_B

gen ln_mu_o_B=ln(mu_o_B)
gen ln_mc_o_B=ln(mc_o_B)

label var  ln_mu_o_B "\$ \mu_{sbjo} \$"
label var  ln_mc_o_B "\$  mc_{sbjo} \$"
	
gen markup_level = ((p_sbjo/mc_o_B)-1)*mc_o_B 

capture drop mu_o_ALT
capture drop ln_mu_o_ALT
gen mu_o_ALT=(alpha_o)^(-1)*theta_buyer
gen ln_mu_o_ALT=ln(mu_o_ALT)
label var  ln_mu_o_ALT "\$ \tilde{\mu}_{sbjo} \$"

* ---------------------------------------------------------------------------- *
* TABLE 6. Buyers' Sourcing, Markups and Costs
* ---------------------------------------------------------------------------- *

do "${floats}\Table6.do"
 
* ---------------------------------------------------------------------------- *
* TABLE E7. Order-Specific Markups and Marginal Costs
* ---------------------------------------------------------------------------- *

do "${floats}\TableE7.do"
 
* ---------------------------------------------------------------------------- *
* TABLE C8. Sourcing and Reliability in Delivery
* ---------------------------------------------------------------------------- *

clonevar ln_mu_sbjo=ln_mu_o_B
do "${floats}\TableC8.do"

* ---------------------------------------------------------------------------- *
* FIGURE C1. Cross-Sectional Variation in the Relational Sourcing Metrics
* ---------------------------------------------------------------------------- *

do "${floats}\FigureC1.do"

* ---------------------------------------------------------------------------- *
* TABLE C10. Within Seller Variaion in Buyers' Sourcing Strategies
* ---------------------------------------------------------------------------- *

sort $isid_vars 
capture drop sample
gen sample=(S_pds==1 & n_ud==1) 	

capture drop b_in_sample
bys b_id: egen b_in_sample=max(sample)

capture drop s_in_sample
bys s_id: egen s_in_sample=max(sample)

bys s_id: egen min_sourcing_s=min(sourcing_metric_b_excl)
bys s_id: egen max_sourcing_s=max(sourcing_metric_b_excl)
gen range_sourcing_s=-min_sourcing+max_sourcing_s

bys s_id: egen n_b_s=nvals(b_id)

foreach x in sourcing_metric_b_excl { 
local CUTOFF 95 90 75 50
foreach n of local CUTOFF{	
capture drop p
egen p = pctile(`x')  if n_b==1 & sourcing_metric_b_excl!=. & b_in_sample==1, p(`n')
capture drop xx
egen xx=mean(p) 
replace p=xx
gen R`n'= (sourcing_metric_b_excl >=p & sourcing_metric_b_excl!=. & b_in_sample==1)
replace  R`n'=. if sourcing_metric_b_excl==. 
}
}

local R R95 R90 R75 R50
foreach r of local R{
capture drop relational
capture drop spot	
clonevar relational=`r'
gen spot=(relational==0 & sourcing_metric_b_excl!=. & b_in_sample==1)
capture drop q_t
capture drop q_r
bys s_id: egen q_t=total(q_exp*(relational==1)+q_exp*(spot==1))
bys s_id: egen q_r=total(q_exp*(relational==1))
gen sh_`r'_s=q_r/q_t
}

do "${floats}\TableC10.do"

* ---------------------------------------------------------------------------- *
* FIGURE C2. Share of Volumes Sold to Relational Buyers
* ---------------------------------------------------------------------------- *

do "${floats}\FigureC2.do"

* ---------------------------------------------------------------------------- *
* FIGURE E1 (Dispersion in markups)
* ---------------------------------------------------------------------------- *

do "${floats}\FigureE1.do"
   
* ---------------------------------------------------------------------------- *
* Create compact data for the robustness runs 
* ---------------------------------------------------------------------------- *

preserve	
rename quarter q_of_order
gen quarter=qofd(date)

keep S_pds n_ud sourcing_metric_b_excl incl_sourcing_metric_b ///
ln_p_sbjo  S_sourcing  ln_q_sb_all sh_s_b sh_b_s age_buysel_month signatory ln_numf_HS6_UD_imp  ///
 ln_q_b_all age_buy_month ln_p_inpf_sbjo ln_q_sbjo ///
gr_sjfot top_dest_b cohort_sb cohort_b  gr_sjt ///
ln_q_b_all ln_q_sb_all sh_s_b sh_b_s  ln_q_b_all age_buy_months age_buysel_months ln_numf_HS6_UD_imp ln_p_inpf_sbjo ln_q_sbjo signatory hhi_seas_sb_norm /// 
sh_max_seas_sbt seas_largest_sbt hhi_j_sb_norm sh_max_j_sbt core_product_sb  ///
 outlier_ln_p_sbjo ///
gr_jt s_id HS6_main date  ///
ln_qf_UD_imp w_r ln_mu_sbjo /// 
sourcing_metric_b_excl SD_incl_sourcing_metric_b S_sourcing SD* /// 
gr_sjfot ln_numf_HS6_UD_imp hhi_seas_sb_norm sh_max_seas_sbt seas_largest_sbt  hhi_j_sb_norm sh_max_j_sbt core_product_sb signatory ln_q_b_all age_buy_month cohort_b ///
  ln_p_inpf_sbjo ln_q_sbjo ln_q_sb_all sh_s_b sh_b_s age_buysel_month cohort_sb HS6_main year quarter month ///
  S_* w_r outlier_ln_p_sbjo s_id b_id top_dest_b 
 

* Generate Alternative Fixed effects
egen gr_jy=group(HS6_main year)
egen gr_jq=group(HS6_main quarter)
egen gr_jm=group(HS6_main month)
egen gr_j=group(HS6_main)
egen gr_y=group(year)
egen gr_q=group(quarter)
egen gr_m=group(month)
egen gr_s=group(s_id)
egen gr_sjy=group(HS6_main year s_id)
egen gr_sjq=group(HS6_main quarter s_id)
egen gr_sjm=group(HS6_main month s_id)
egen gr_sy=group( year s_id)
egen gr_sq=group( quarter s_id)
egen gr_sm=group( month s_id)
egen gr_sj=group( HS6_main s_id)
egen gr_d=group( top_dest_b )
egen gr_dy=group( top_dest_b year )
egen gr_dq=group( top_dest_b quarter )
egen gr_dm=group( top_dest_b month )
egen gr_dj=group( top_dest_b HS6_main )
egen gr_djy=group( top_dest_b year HS6_main)
egen gr_djq=group( top_dest_b quarter HS6_main)
egen gr_djm=group( top_dest_b month HS6_main)
egen gr_ds=group( top_dest_b s_id)
egen gr_dsj=group( top_dest_b s_id HS6_main)
egen gr_dsjy=group( top_dest_b s_id HS6_main year)

* Generate  Samples:
gen sample2=(n_ud==1 & S_pds==1) // baseline

order S_pds n_ud sourcing_metric_b_excl incl_sourcing_metric_b ///
ln_p_sbjo  S_sourcing  ln_q_sb_all sh_s_b sh_b_s age_buysel_month signatory ln_numf_HS6_UD_imp  ///
 ln_q_b_all age_buy_month ln_p_inpf_sbjo ln_q_sbjo ///
gr_sjfot top_dest_b cohort_sb cohort_b  gr_sjt ///
ln_q_b_all ln_q_sb_all sh_s_b sh_b_s  ln_q_b_all age_buy_months age_buysel_months ln_numf_HS6_UD_imp ln_p_inpf_sbjo ln_q_sbjo signatory hhi_seas_sb_norm /// 
sh_max_seas_sbt seas_largest_sbt hhi_j_sb_norm sh_max_j_sbt core_product_sb  ///
 outlier_ln_p_sbjo ///
gr_jt s_id HS6_main date  ///
ln_qf_UD_imp w_r ln_mu_sbjo /// 
sourcing_metric_b_excl SD_incl_sourcing_metric_b S_sourcing SD* /// 
gr_sjfot ln_numf_HS6_UD_imp hhi_seas_sb_norm sh_max_seas_sbt seas_largest_sbt  hhi_j_sb_norm sh_max_j_sbt core_product_sb signatory ln_q_b_all age_buy_month cohort_b ///
  ln_p_inpf_sbjo ln_q_sbjo ln_q_sb_all sh_s_b sh_b_s age_buysel_month cohort_sb HS6_main year quarter month ///
  S_* w_r outlier_ln_p_sbjo s_id b_id top_dest_b 
  
  sort *

   
save "${replicated_data}\Robustness_Data.dta", replace

restore	
	
* ---------------------------------------------------------------------------- *
* FIGURE 2. Robustness of Price Result to Alternative Fixed Effects and Controls
* ---------------------------------------------------------------------------- *

preserve
do "${floats}\Figure2.do"
restore 

* ---------------------------------------------------------------------------- *
* FIGURE 3. Robustness of Markups Result to Alternative Fixed Effects and Controls
* ---------------------------------------------------------------------------- *

preserve
do "${floats}\Figure3.do"
restore 
 
 
* ---------------------------------------------------------------------------- *
* Bringing in Relationship Level Data
* ---------------------------------------------------------------------------- *

*use "${data}\TEMPDATAFILE.dta", clear

sort b_id s_id
capture drop _merge
merge m:1 b_id s_id using "${source_data}\Relationship_Level_Data.dta" 
drop if _merge==2

capture drop sample
gen sample=(S_pds==1 & n_ud==1) 	
capture drop sb_in_sample
bys b_id s_id: egen sb_in_sample=max(sample)


* ---------------------------------------------------------------------------- *
* TABLE C5. Correlation of Sourcing Measures and the Buyer and Relationship Levels
* ---------------------------------------------------------------------------- *

do "${floats}\TableC5PanelA.do"
do "${floats}\TableC5PanelB.do"

* ---------------------------------------------------------------------------- *
* TABLE C6. Relational Buyers and Relationships
* ---------------------------------------------------------------------------- *

label var Msourcing_metric_sb "\$Relational_{sb}\$"
label var Msourcing_metric_b  "\$Relational_{b}\$"
label var Mwav_sourcing_metric_b "\$\widetilde{Relational}_b\$" 
label var Mdwav_sourcing_metric_sb "\$\widetilde{Relational}_{sb}\$" 
label var Mav_sourcing_metric_b "\$\widetilde{Relational}_b\$" 
label var Mdav_sourcing_metric_sb "\$\widetilde{Relational}_{sb}\$" 

label var sourcing_metric_b_excl "\$Relational_{b}\$"
label var Msourcing_metric_sbe "\$Relational_{sb}\$"
label var Mwav_sourcing_metric_be "\$\widetilde{Relational}_b\$" 
label var Mdwav_sourcing_metric_sbe "\$\widetilde{Relational}_{sb}\$" 
label var Mav_sourcing_metric_be "\$\widetilde{Relational}_b\$" 
label var Mdav_sourcing_metric_sbe "\$\widetilde{Relational}_{sb}\$" 

gen Mdav_sourcing_metric_sbm=-1*(abs(Msourcing_metric_sb)-abs(Mav_sourcing_metric_be))
gen Mdwav_sourcing_metric_sbm=-1*(abs(Msourcing_metric_sb)-abs(Mwav_sourcing_metric_be))
 
* Discretize the buyer metric: 

capture drop TEMP_SAMPLE
capture drop sample
gen sample=(S_pds==1 & n_ud==1) 
reghdfe ln_p_sbjo  sourcing_metric_b_excl ln_q_sb_all sh_s_b sh_b_s age_buysel_month    signatory  ///
 ln_q_b_all age_buy_month ln_p_inpf_sbjo ln_q_sbjo  if sample==1, ///
abs(gr_sjt top_dest_b cohort_sb cohort_b ) vce (cluster b_id)
gen TEMP_SAMPLE=e(sample)
capture drop b_in_TEMP_SAMPLE
bys b_id: egen b_in_TEMP_SAMPLE=max(TEMP_SAMPLE)

capture drop dummy
qui: sum Mwav_sourcing_metric_be if n_b==1 & b_in_TEMP_SAMPLE==1, d
gen dummy=(Mwav_sourcing_metric_be>=r(p90))
replace dummy=. if Mwav_sourcing_metric_be==.
label var dummy  "\$Relational^{0/1}_{b}\$"
 
replace sample=TEMP_SAMPLE 
 
do "${floats}\TableC6.do"
  
* ---------------------------------------------------------------------------- *
* TABLE C4. Explanatory Power of Relationship Match Values
* ---------------------------------------------------------------------------- *

capture drop gr_sb
egen gr_sb=group(s_id b_id)
do "${floats}\TableC4.do"

* ---------------------------------------------------------------------------- *
* TABLE D1. Buyers' Sourcing and Input Usage: Alternative Time Horizons
* ---------------------------------------------------------------------------- *

do "${floats}\TableD1.do" 

* ---------------------------------------------------------------------------- *
* TABLE D3. Alternative Definitions of Buyers' Relational Sourcing
* ---------------------------------------------------------------------------- *

sort b_id 
capture drop _merge
merge m:1 b_id using "${source_data}\Alternative_Measures.dta" 
drop if _merge==2

capture drop sample
gen sample=(S_pds==1 & n_ud==1) 	
capture drop b_in_sample
bys b_id: egen b_in_sample=max(sample)

bys b_id: egen num_s_wov=nvals(s_id)
gen ln_num_s_wov=ln(num_s_wov)
gen ln_num_s_b_ALL=ln(num_s_b_ALL)

capture drop n_b
sort b_id $isid_vars
bys b_id: gen n_b=_n
local VAR  ln_num_s_b_ALL num_s_wov num_s_b_ALL sourcing_alt_1 sourcing_alt_2 sourcing_alt_3 sourcing_alt_4 sourcing_alt_5 sourcing_alt_6 sourcing_alt_7 sourcing_alt_8 wav_num_m_sb FE_num_m_sb wav_num_m_sb_mya sourcing_l_hhi sourcing_l_hhin sourcing_l_alt_hhi sourcing_l_alt_hhin sourcing_all_hhin sourcing_l_1 sourcing_l_3 sourcing_l_5 sourcing_l_all_1 sourcing_l_all_3 sourcing_l_all_5 nl_s50 nl_s70 nq_s50 nq_s70
foreach v of local VAR{
capture drop S_`v'	
capture drop xx
capture drop mean_xx
capture drop sd_xx
gen xx=`v' if n_b==1 & b_in_sample==1 & `v'!=0 & S_sourcing!=.
egen mean_xx=mean(xx)
egen sd_xx=sd(xx)
gen S_`v'=(`v'-mean_xx)/sd_xx
replace S_`v'=. if `v'==0
replace S_`v'=. if b_in_sample!=1    // Standarized variable only defined for buyers in sample
replace S_`v'=. if S_sourcing==.  
}
capture drop xx mean_xx sd_xx

reghdfe ln_p_sbjo  S_sourcing  ln_q_sb_all sh_s_b sh_b_s age_buysel_month signatory  ///
 ln_q_b_all age_buy_month ln_p_inpf_sbjo ln_q_sbjo ///
if sample==1, ///
abs(gr_sjt top_dest_b cohort_sb cohort_b) vce (cluster b_id)
capture drop sample
gen sample=e(sample)

do "${floats}\TableD3.do"

* ---------------------------------------------------------------------------- *
* FIGURES E2 and E3 (Assumptions on input allocations)
* ---------------------------------------------------------------------------- * 

capture drop _merge 
sort custom_office registration_nber itm_nber date
merge 1:1 custom_office registration_nber itm_nber date using "${source_data}\In_Sample_Outliers.dta" 

* 1) Proportional allocation of material inputs

capture drop xx 
gen xx=exp(ln_qf_UD_imp) if n_ud==1 & S_pd==1 
bys gr_st: egen qf_st=total(xx)
	
capture drop xx 
gen xx=exp(ln_q_sbjo) if n_ud==1 & S_pd==1 
bys gr_sjt: egen q_sjt=total(xx)
bys gr_st: egen q_st=total(xx)
gen sh_j_st=q_sjt/q_st				
gen qf_sjt=sh_j_st*qf_st 
gen sh_o_sjt=exp(ln_q_sbjo)/q_sjt 
gen fake_w_r = sh_o_sjt*qf_sjt/exp(ln_q_sbjo) 
gen diff_w_r= (fake_w_r - w_r)/w_r
gen abs_diff_w_r=abs(diff_w_r)	

* ---------------------------------------------------------------------------- *
* FIGURE E2. Comparison of Weight Rations with Imputed Input Allocations
* ---------------------------------------------------------------------------- *

do "${floats}\FigureE2.do"

* ---------------------------------------------------------------------------- *
* FIGURE E3. Comparison of Fabric Price with Imputed Common Price
* ---------------------------------------------------------------------------- *

capture drop xx 
gen xx=p_inpf_sbjo  if n_ud==1 & S_pd==1  
bys HS6_main year: egen av_pf_jy=mean(xx)
gen diff_pf= (av_pf_jy - p_inpf_sbjo)/p_inpf_sbjo
gen abs_diff_pf=abs(diff_pf)	

do "${floats}\FigureE3.do"

* ---------------------------------------------------------------------------- *
* TABLE E2. Buyers' Sourcing and Input Substitutes
* ---------------------------------------------------------------------------- *

do "${floats}\TableE2.do"

* ---------------------------------------------------------------------------- *
* TABLE D6. The Downstream Market
* ---------------------------------------------------------------------------- *

do "${floats}\TableD6.do"


* ---------------------------------------------------------------------------- *
* EXTRACT SAMPLE INDICATORS FROM WORKING SAMPLE (FOR LATER USE)
* ---------------------------------------------------------------------------- *

preserve
isid custom_office registration_nber itm_nber date
keep custom_office registration_nber itm_nber date /// 
S_p S_pds n_ud sourcing_metric_b_excl D_sourcing S_sourcing incl_sourcing_metric_b ///
ln_p_inpf_sbjo ln_p_sbjo ln_q_sbjo ln_mu_sbjo
duplicates drop 
sort custom_office registration_nber itm_nber date
save "${replicated_data}\In_Sample_Observations.dta", replace 
restore
 
* ---------------------------------------------------------------------------- *
* DATA PREPARATION FOR VF CASE
* ---------------------------------------------------------------------------- *

preserve 

capture drop xx
gen xx=(b_id==1915)
bys s_id: egen trades_with_VF=max(xx)
gen buyer_is_VF=(b_id==1915)
keep if trades_with_VF==1

distinct s_id
distinct b_id 

capture label var D_sourcing "\$Relational^D_b\$" 
capture label var S_sourcing "\$Relational_b\$" 

gen year_o = year(date_of_order)
gen month_o = month(date_of_order)

egen product = group(HS6_m)

* 1) Treatment definitions:

gen VF = 0 
replace VF = 1 if  b_id == 1915
gen post = 0 
replace post = 1 if year > 2010
gen T = VF * post 

* 2) VF's process and counts of firms
cap drop gr_sb
egen gr_sb=group(s_id b_id)

capture drop xx
gen xx=s_id if year==cohort_sb
bys b_id year: egen num_news_by=nvals(xx)
capture drop yy 
bys b_id year: egen yy=mean(num_news_by)
replace num_news_by=yy

bys b_id year: egen num_sel_by=nvals(s_id)
bys b_id post: egen num_sel_post=nvals(s_id)

bys s_id: egen post_seller=max(post==1 & VF==1)
bys s_id: egen pre_seller=max(post==0 & VF==1)
gen pre_post_seller=(post_seller==1 & pre_seller==1)

tab trades_with_VF pre_post_seller if n_s==1
tab trades_with_VF post_seller if n_s==1
tab trades_with_VF pre_seller if n_s==1

tab year if VF==1, sum(num_news_by)
tab year if VF==1, sum(num_sel_by)
gen sh_new_all=num_news_by/num_sel_by
tab year if VF==1, sum(sh_new_all)

bys s_id year: egen q_sy_VF=total(q_exp*VF)
bys s_id year: egen q_sy=total(q_exp)
gen sh_VF_sy=q_sy_VF/q_sy

bys s_id year:  gen n_sy=_n

* The share of VF increases: 
tab year if n_sy==1 & pre_post_seller==1, sum(sh_VF_sy)

* Churning of other buyers:
bys s_id b_id: egen end_sb=max(date)
replace end_sb=yofd(end_sb)

capture drop xx
gen xx=b_id if year==end_sb & VF==0
bys s_id year: egen end_b_sy=nvals(xx)
capture drop yy
bys s_id year: egen yy=mean(end_b_sy)
replace end_b_sy=yy
replace end_b_sy=0 if end_b_sy==.

capture drop xx
gen xx=b_id if year==cohort_sb & VF==0
bys s_id year: egen new_b_sy=nvals(xx)
capture drop yy
bys s_id year: egen yy=mean(new_b_sy)
replace new_b_sy=yy
replace new_b_sy=0 if new_b_sy==.

capture drop xx
gen xx=b_id if  VF==0
bys s_id year: egen nb_sy=nvals(xx)
capture drop yy
bys s_id year: egen yy=mean(nb_sy)
replace nb_sy=yy
replace nb_sy=0 if nb_sy==.

label var post "\$Post\$"
label var nb_sy "\$Count^b_{sy}\$"
label var end_b_sy "\$Count^{ends}_{sy}\$"
label var new_b_sy "\$Count^{starts}_{sy}\$"

* 3) Identifying the relevant control

egen mp = group(product month)			
egen sjy = group(s_id product year) 	
egen by = group(b_id  year) 			
egen gr_by=group(b_id year)
capture drop sample
gen sample=(n_ud==1 & S_pds==1)

* 4) Samples

capture drop q_sy 
capture drop q_sby 
bys s_id b_id year: egen q_sby=total(q_exp)
bys s_id year: egen q_sy=total(q_exp)
bys s_id year: egen q_sy_nonVF=total(q_exp*(VF==0))
gen sh_buy_sy=q_sby/q_sy
gen sh_buy_sy_nonVF=q_sby/q_sy_nonVF

tab year if VF==1, sum(sh_buy_sy)
tab year if VF==0, sum(sh_buy_sy_nonVF)

bys s_id b_id post: egen q_sbp=total(q_exp)
bys s_id post: egen q_sp=total(q_exp)
bys s_id post: egen q_sp_nonVF=total(q_exp*(VF==0))
gen sh_buy_sp=q_sbp/q_sp
gen sh_buy_sp_nonVF=q_sbp/q_sp_nonVF
tab year if VF==0, sum(sh_buy_sp_nonVF)
capture drop xx
gen xx=sh_buy_sp if VF==1
bys s_id post: egen sh_VF_sp=max(xx)

label var year "\$Year\$"
label var VF "\$VF_o\$"
  
* ---------------------------------------------------------------------------- *
* FIGURE 4. A Change in Sourcing Strategy
* ---------------------------------------------------------------------------- *

do "${floats}\Figure4.do"

* ---------------------------------------------------------------------------- *
* TABLE C7. A Change in Sourcing Strategy - VF's Case
* ---------------------------------------------------------------------------- *

do "${floats}\TableC7.do"

restore

* ---------------------------------------------------------------------------- *
* DATA PREPARATION FOR HARTALS ANALYSIS
* ---------------------------------------------------------------------------- *

sort date
capture drop _merge
merge m:1 date using "${source_data}\Hartals_Data.dta"
drop if _merge==2

gen hartal_ongoing=(_merge==3)

gen hartal_period=0
capture drop xx
gen xx=date if hartal_ongoing==1
levelsof xx, local(DD)
foreach d of local DD{
replace hartal_period=1	if date>=`d'-5 & date<=`d'+5
}

bys UD_num: egen UD_ships_in_hartal=max(hartal_ongoing)
bys UD_num: egen UD_ships_in_period=max(hartal_period)

egen date_ac=concat(Announced_Day Announced_Month Announced_Year) , punct("/")
gen date_anounce=date(date_ac,"DMY",2015)
format date_anounce %td

gen anouncement=(date-date_anounce)
replace anouncement=. if hartal_ongoing==0

gen hartal_order=0
capture drop xx
gen xx=date if hartal_ongoing==1
bys UD_num: egen min_d=min(date)
bys UD_num: egen max_d=max(date)
levelsof xx, local(DD)
foreach d of local DD{
replace hartal_order=1	if `d'>=min_d-7 & `d'<=max_d+7
}

gen duration_UD=max_d-min_d+1

gen hartal_order_anounced=0
capture drop xx
gen xx=date if hartal_ongoing==1
levelsof xx, local(DD)
foreach d of local DD{
replace hartal_order_anounced=1	if `d'>=min_d-7 & `d'<=max_d+7 & anouncement>3
}

bys UD_num date: gen n_udd=_n 

capture drop av_length_hartal
capture drop av_anounce_hartal
capture drop xx
gen xx=Length if n_udd==1
bys UD_num: egen av_length_hartal=mean(xx)
capture drop xx
gen xx=anouncement if n_udd==1
bys UD_num: egen av_anounce_hartal=mean(anouncement)

capture drop sample
gen sample=(n_ud==1 & S_pds==1)

tab hartal_order   if sample==1
tab UD_ships_in_hartal if sample==1
tab UD_ships_in_period if sample==1

bys UD_num: egen num_ship_ud=nvals(date)
sort UD_num date 
by UD_num: gen between_ship=date-date[_n-1]
replace between_ship=. if between_ship==0 

bys UD_num: egen med_between_ship=median(between_ship)
bys UD_num: egen av_between_ship=mean(between_ship)

bys UD_num: egen av_q_ship=mean(q_exp)
gen ln_av_q_ship=ln(av_q_ship)

tab hartal_order D_sourcing if sample==1

tab hartal_order D_sourcing if n_ud==1

label var hartal_order "\$Hartal_{sbjo}\$"
label var duration_UD "\$Duration_{sbjo}\$"
label var num_ship_ud "\$Count^{ship}_{sbjo}\$"
label var ln_av_q_ship "\$\overline{q}^{ship}_{sbjo}\$"
label var UD_ships_in_period "\$Ships \ in \ Hartal_{sbjo}\$"  

capture drop gr_sb
egen gr_sb=group(s_id b_id)

gen ln_duration=ln(duration_UD)
label var ln_duration "\$Duration_{sbjo}\$"

* ------------------------------------------------------------------------------ *
* TABLE C12. Orders Affected by Hartals
* ------------------------------------------------------------------------------ *

do "${floats}\TableC12.do"

* ---------------------------------------------------------------------------- *
* DATA PREPARATION FOR ROBUSTNESS IN SUBSAMPLE
* ---------------------------------------------------------------------------- *

capture drop _merge 
sort custom_office registration_nber itm_nber date
merge 1:1 custom_office registration_nber itm_nber date using "${source_data}\In_Sample_Outliers.dta" 
	
sort s_id 
capture drop _merge
merge m:1 s_id using "${source_data}\Match_Production_Customs_IDs_NoFII.dta" 
drop if _merge==2	
gen Production_code=(_merge==3)

capture drop sample
gen sample=(n_ud==1 & S_pds==1)
capture drop sample2
gen sample2=(n_ud==1 & S_pd==1)

tab sample Production_code
tab sample2 Production_code

capture drop in_labor_data
capture drop LAB_*
bys b_id: egen in_labor_data=max(sample)

capture drop _merge
sort b_id 
merge m:1 b_id using "${replicated_data}\Sample_b_PD.dta"
drop if _merge==2
capture drop in_labor_data
gen in_labor_data=(_merge==3)

label var D_sourcing "\$Relational^D_b\$" 
label var S_sourcing "\$Relational_b\$" 

capture drop sample
gen sample=(n_ud==1 & S_pd==1)

capture drop qq
capture drop QQ
bys s_id: egen QQ=total(q_exp)
bys s_id: egen qq=total(q_exp*(in_labor_data==1))
replace qq=qq/QQ 
sum qq if sample==1, d

capture drop s_in_labor_data
gen s_in_labor_data=qq>=0.5

* ---------------------------------------------------------------------------- *
* TABLE D5. Input Usage, Prices and Markups: Robustness in the Production Subsample
* ---------------------------------------------------------------------------- *

do "${floats}\TableD5.do"


	

